extends Node

@export var ball_sence:PackedScene
var ball_images := []
# 主球
var cue_ball
# 主球初始位置 
const START_POS = Vector2(890,340)
# 最大力量
const MAX_POWER = 6
# 是否正在射击
var taking_shoot :bool = true
# 移动阈值，移动速度低于此值时，将球设置为静止
const MOVE_THRESHOLD = 5
# 主球是否进洞
var cue_ball_potted:bool = false
# 记录进洞的球
var potted :=[]

# 记录击打的次数
var shoot_count:int = 0

# Called when the node enters the scene tree for the first time.
func _ready():
	load_images()
	new_game()
	$"台球桌"/"球洞".body_entered.connect(potted_ball)
	$Hud/"结果面板"/"按钮-继续".pressed.connect(game_continue)
	$Hud/"结果面板"/"按钮-重新开始".pressed.connect(new_game)
	
func load_images():
	for i in range(1, 17, 1):
		var filename = str("res://assets/ball_", i, ".png")	
		ball_images.append(filename)


func clear_balls():
	get_tree().call_group("球", "queue_free")
	
	for b in potted:
		b.queue_free()
	potted.clear()

func new_game():
	$Hud.hide()
	shoot_count = 0
	update_infos()
	
	clear_balls()
	
	generate_balls()	
	reset_cue_ball()
	show_cue()
	get_tree().paused = false
	
	
	 
func update_infos():
	$"标签-射击次数".text = "击打次数："+str(shoot_count)
	
func generate_balls():
	var count = 0
	var rows = 5
	var dia = 36
	for col in range(5):
		for row in range(rows):
			var b = ball_sence.instantiate()
			var pos = Vector2(250 + (col * dia), 267 + (row * dia) + (col*dia/2))
			add_child(b)
			b.position = pos
			b.get_node("skin").texture = load(ball_images[count])
			count+=1
		rows-=1

func reset_cue_ball():
	cue_ball = ball_sence.instantiate()
	add_child(cue_ball)
	cue_ball.position = START_POS
	cue_ball.get_node("skin").texture = load(ball_images.back())
	taking_shoot = false
	cue_ball_potted = false

func show_cue():
	$"球杆".set_process(true)
	$"球杆".position = cue_ball.position
	$"球杆".show()
	
	$"能量条".position.x = cue_ball.position.x - (0.5 * $"能量条".size.x)
	$"能量条".position.y = cue_ball.position.y + ($"能量条".size.y)
	$"能量条".show()

func hide_cue():
	$"球杆".set_process(false)
	$"球杆".hide()
	$"能量条".hide()

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	if(Input.is_key_pressed(KEY_ESCAPE) and get_tree().paused == false):
		game_pause()
	
	var moving = false
	for b in get_tree().get_nodes_in_group("球"):
		print(b.linear_velocity.length())
		var v = b.linear_velocity.length()
		if(v>0 and v<MOVE_THRESHOLD):
			b.sleeping = true
		elif b.linear_velocity.length() >= MOVE_THRESHOLD:
			moving = true

	print(moving)

	if not moving:
		if cue_ball_potted:
			reset_cue_ball()
		if not taking_shoot:
			taking_shoot = true
			show_cue()
	else:
		if taking_shoot:
			taking_shoot = false
			hide_cue()		

# 当球杆击打时
func _on_cue_shoot(power):
	# 给球冲击力
	cue_ball.apply_central_impulse(power)
	$sounds/kick_ball.play()
	shoot_count+=1
	update_infos()
	
	
func potted_ball(body):
	$sounds/ball_in.play()
	
	if( body==cue_ball):
		# 白球进洞，清除白球，在_process会判断 cue_ball_potted 再重置白球
		cue_ball_potted = true
		remove_child(cue_ball)
		cue_ball.queue_free()
	else:
		# 其他球进洞
		# 创建一个球的图像，展示到进球面板
		var b = Sprite2D.new()
		add_child(b)
		b.texture = body.get_node("skin").texture
		potted.append(b)	
		b.position = Vector2(50 * potted.size(), 725)

		# 删除原带刚体的球
		body.queue_free()
		
		if potted.size() == 15:
			game_over()

func game_pause():
	get_tree().paused = true
	$Hud.show()
	$Hud/"结果面板"/Label.text="暂停游戏"
	$Hud/"结果面板"/"按钮-继续".show()
	pass
	
func game_continue():
	print(111111111)
	get_tree().paused = false
	$Hud.hide()
	pass	

func game_over():
	$Hud/"结果面板"/Label.text="你赢了！"
	$Hud/"结果面板"/"按钮-继续".hide()
	hide_cue()
	get_tree().paused = true
	$Hud.show()



